import { Component, ViewChild } from '@angular/core';
import { Platform, Nav, IonicApp, ToastController, Keyboard } from 'ionic-angular';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { WechatProvider } from '../providers/wechat/wechat';
import { UnitsProvider } from '../providers/units/units';
import { CodepushProvider } from '../providers/codepush/codepush';
import { JpushProvider } from '../providers/jpush/jpush';
import { JmessageProvider } from "../providers/jmessage/jmessage";
import { NetworkInformationProvider } from "../providers/network-information/network-information";
import { DialogProvider } from '../providers/dialog/dialog';
import { TabsPage } from '../pages/tabs/tabs';
import { UserDataService } from '../providers/service/user-data.service';
import { UserInfoProvider } from '../providers/user-info/user-info';
import { HttpProvider } from '../providers/http/http';
import { Network } from '@ionic-native/network';
import { StorageProvider } from '../providers/storage/storage';
import { BleProvider } from '../providers/ble/ble';

@Component({
	templateUrl: 'app.html'
})
export class MyApp {

	public rootPage: any;

	backButtonPressed: boolean = false; //用于判断返回键是否触发

	public loginInfo = {
		UserName: '',
		PassWord: '',
		isAutomaticLogon: false
	};

	// 登录信息
	userInfo: user_info = new user_info();

	@ViewChild('myNav') nav: Nav;
	constructor(
		public platform: Platform,
		public statusBar: StatusBar,
		public splashScreen: SplashScreen,
		public wechat: WechatProvider,
		public units: UnitsProvider,
		public codepush: CodepushProvider,
		public jpush: JpushProvider,
		public jmessage: JmessageProvider,
		public netDetect: NetworkInformationProvider,
		public ionicApp: IonicApp,
		public toastCtrl: ToastController,
		public dialog: DialogProvider,
		public userData: UserDataService,
		public user: UserInfoProvider,
		public http: HttpProvider,
		private network: Network,
		public storage: StorageProvider,
		public keyboard: Keyboard,
		public ble: BleProvider,
	) {
		this.platform.ready().then(() => {
			// Okay, so the platform is ready and our plugins are available.
			// Here you can do any higher level native things you might need.

			this.netDetect.netDetect();

			//注册返回按键事件
			this.registerBackButtonAction();

			// 自动登录判断
			this.automaticLogon();

			//判断微信页面
			// if (this.units.isWechat()) {
			// 	this.wechat.wechat_login();
			// 	this.rootPage = "TabsPage";
			// } else {
			// 	this.rootPage = "LoginPage";
			// }

			this.statusBar.styleDefault();
			// this.splashScreen.hide();
			//格式化
			if (this.platform.is('cordova')) {
				//app更新
				this.codepush.initCodePush();
				//极光推送
				this.jpush.initJpush();
				this.jpush.receiveNotification();
				this.jpush.openNotification();
				//极光IM
				this.jmessage.initJmessage();
			}
		});
	}

	// 注册android返回按键事件
	registerBackButtonAction() {
		this.platform.registerBackButtonAction((): any => {
			//按下返回键时，先关闭键盘
			if (this.keyboard.isOpen()) {
				//按下返回键时，先关闭键盘
				this.keyboard.close();
				return;
			};
			let activePortal = this.ionicApp._modalPortal.getActive() || this.ionicApp._overlayPortal.getActive();
			let loadingPortal = this.ionicApp._loadingPortal.getActive();
			if (activePortal) {
				//其他的关闭
				activePortal.dismiss({ code: 0 }).catch(() => {
				});
				activePortal.onDidDismiss((data) => {
					if (data.code === 0) {
						this.ble.disconect();
					}
				});
				return;
			}
			if (loadingPortal) {
				//loading的话，返回键无效
				return;
			}

			// 获取已激活页面
			let activeVC = this.nav.getActive();
			let page = activeVC.instance;
			if (!(page instanceof TabsPage)) {
				if (!this.nav.canGoBack()) {
					// 当前页面为tabs，退出APP
					return this.showExit();
				}
				// 当前页面为tabs的子页面，正常返回
				return this.nav.pop();
			}
			let tabs = page.tabRef;
			let activeNav = tabs.getSelected();
			if (!activeNav.canGoBack()) {
				// 当前页面为tab栏，退出APP
				return this.showExit();
			}
			// 当前页面为tab栏的子页面，正常返回
			return activeNav.pop();
		}, 101);
	}


	//双击退出提示框
	async showExit() {
		if (this.backButtonPressed) { //当触发标志为true时，即2秒内双击返回按键则退出APP
			this.platform.exitApp();
		} else {
			this.toastCtrl.create({
				message: '再按一次退出应用',
				duration: 2000,
				position: 'bottom'
			}).present();
			this.backButtonPressed = true;
			setTimeout(() => this.backButtonPressed = false, 2000);//2秒内没有再次点击返回则将触发标志标记为false
		}
	}

	/**
	 * 自动登录
	 */
	async automaticLogon() {
		let a = await this.userData.find((user) => user.key !== '');
		if (a.length === 0) {
			// this.dialog.showToast('提示', '登录失败请重试');
			this.rootPage = "LoginPage";
			setTimeout(() => { 
				this.splashScreen.hide();
		   }, 1000)
			return;
		}
		if (a.length > 0) {
			var params = {
				username: a[0].phone,
				password: a[0].password,
				isAutomaticLogon: a[0].isAutomaticLogon
			};
			if (params.isAutomaticLogon === false) {
				this.rootPage = "LoginPage";
				setTimeout(() => { 
					this.splashScreen.hide();
			   }, 1000)
				return;
			}
			if (this.network.type === 'none' || this.network.type === '2g') {
				let a = await this.userData.find((user) => user.key !== '');
				if (a[0].password === params.password && a[0].phone === params.username) {
					this.user.setuserInfo(a[0]);
					// this.navCtrl.push('TabsPage');
					this.rootPage = "TabsPage";
					setTimeout(() => { 
						this.splashScreen.hide();
				   }, 1000)
				} else { this.dialog.showToast('提示', '当前无网络只能登陆上一次登陆的用户'); }
				return;
			}
			let res = await this.http.postJson('', 'users/member/login', { 'phone': params.username, 'password': params.password }, '')

			if (res['status'] == 200) {
				//this.dialog.showAlert('您好'+res['data']['nickname'], res['message']);		
				this.http.login_stuta = 1;
				res['data']['password'] = params.password;
				// this.storage.saveStorage("login_info", res['data']);
				this.userInfo = res['data'];
				this.user.setuserInfo(this.userInfo);
				this.http.setAuthorization(res['data']['access_token']);//该令牌唯一表示该用户、用户的组和用户的特权。系统使用令牌控制用户可以访问哪些安全对象，并控制用户执行相关系统操作的能力
				this.getdictionary();
				// this.navCtrl.push('TabsPage');
				this.rootPage = "TabsPage";
			} else {
				this.toastCtrl.create({
					message: res['message'],
					duration: 2000,
					position: 'top'
				}).present();
				this.rootPage = "LoginPage";
				setTimeout(() => { 
					this.splashScreen.hide();
			   }, 1000)
			}
			// this.rootPage = "TabsPage";
			// this.splashScreen.hide();//启动后关闭splashscreen页面（不用设置）
		}
		else {
			this.rootPage = "LoginPage";
			setTimeout(() => { 
				this.splashScreen.hide();
		   }, 3000)
		}



	}

	/**
	 * 获取数据字典
	 */
	getdictionary() {
		this.http.postJson('', 'aindex/dictionary/index',
			{
				select: "m.D_GROUP",
				joinWith: "group", "groupby": "D_GROUP", "indexBy": "D_GROUP", "limit": 0,
				where: ["<>", "s_dictionary.D_STATE", 0]
			}, '')
			.then(res => {
				if (res['status'] == 200) {
					this.storage.saveStorage("dictionary", JSON.stringify(res['data']));
				}
			});
	}
}


export class user_info {
	member_id: any;
	nickname: any;
	phone: any;
	balance: any;
	local_balance: any;
	member_state: any;
	created_at: any;
	updated_at: any;
	cuser_id: any;
	uuser_id: any;
	is_del: any;
	password: any;
	file_type_id: any;
	access_token: any;
	isAutomaticLogon: any;
}